import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path/path.dart' as path;
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:device_info_plus/device_info_plus.dart';
import '../utils/k_log.dart';

class FileDownloadUtils {
  /// 下载assets中的PDF文件到手机存储
  static Future<bool> downloadAssetPdfToPhone({
    required String assetPath,
    required String fileName,
  }) async {
    try {
      // 显示加载提示
      EasyLoading.show(status: '正在下载...');

      // 检查存储权限
      bool hasPermission = await _checkStoragePermission();
      if (!hasPermission) {
        EasyLoading.dismiss();
        Get.snackbar(
          '权限不足',
          '需要存储权限才能下载文件',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Get.theme.colorScheme.error,
          colorText: Get.theme.colorScheme.onError,
        );
        return false;
      }

      // 从assets读取文件
      ByteData data = await rootBundle.load(assetPath);
      Uint8List bytes = data.buffer.asUint8List();

      // 获取下载目录
      Directory? downloadDir = await _getDownloadDirectory();
      if (downloadDir == null) {
        EasyLoading.dismiss();
        Get.snackbar(
          '下载失败',
          '无法获取下载目录',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Get.theme.colorScheme.error,
          colorText: Get.theme.colorScheme.onError,
        );
        return false;
      }

      // 创建文件路径
      String filePath = path.join(downloadDir.path, fileName);
      
      // 如果文件已存在，添加时间戳避免重复
      if (await File(filePath).exists()) {
        String nameWithoutExt = path.basenameWithoutExtension(fileName);
        String ext = path.extension(fileName);
        String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
        fileName = '${nameWithoutExt}_$timestamp$ext';
        filePath = path.join(downloadDir.path, fileName);
      }

      // 写入文件
      File file = File(filePath);
      await file.writeAsBytes(bytes);

      EasyLoading.dismiss();
      
      // 显示成功提示
      Get.snackbar(
        '下载成功',
        '文件已保存到: ${downloadDir.path}/$fileName',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Get.theme.colorScheme.primary,
        colorText: Get.theme.colorScheme.onPrimary,
        duration: const Duration(seconds: 3),
      );

      KLog.d('文件下载成功: $filePath');
      return true;
    } catch (e) {
      EasyLoading.dismiss();
      KLog.e('文件下载失败: $e');
      
      Get.snackbar(
        '下载失败',
        '文件下载过程中出现错误',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Get.theme.colorScheme.error,
        colorText: Get.theme.colorScheme.onError,
      );
      return false;
    }
  }

  /// 检查存储权限
  static Future<bool> _checkStoragePermission() async {
    if (Platform.isAndroid) {
      // Android 13+ 不需要存储权限，直接返回true
      if (await _getAndroidSdkVersion() >= 33) {
        return true;
      }
      
      // Android 13以下需要存储权限
      PermissionStatus status = await Permission.storage.status;
      if (status.isGranted) {
        return true;
      }
      
      if (status.isDenied) {
        status = await Permission.storage.request();
        return status.isGranted;
      }
      
      return false;
    } else if (Platform.isIOS) {
      // iOS不需要额外权限
      return true;
    }
    
    return false;
  }

  /// 获取Android SDK版本
  static Future<int> _getAndroidSdkVersion() async {
    try {
      if (Platform.isAndroid) {
        DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
        AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        return androidInfo.version.sdkInt;
      }
    } catch (e) {
      KLog.e('获取Android SDK版本失败: $e');
    }
    return 0;
  }

  /// 获取下载目录
  static Future<Directory?> _getDownloadDirectory() async {
    try {
      if (Platform.isAndroid) {
        // Android优先使用Downloads目录
        Directory? downloadDir = Directory('/storage/emulated/0/Download');
        if (await downloadDir.exists()) {
          return downloadDir;
        }
        
        // 备选方案：使用外部存储目录
        Directory? externalDir = await getExternalStorageDirectory();
        if (externalDir != null) {
          Directory downloadDir = Directory(path.join(externalDir.path, 'Download'));
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
          return downloadDir;
        }
        
        // 最后备选：应用文档目录
        return await getApplicationDocumentsDirectory();
      } else if (Platform.isIOS) {
        // iOS使用文档目录
        return await getApplicationDocumentsDirectory();
      }
    } catch (e) {
      KLog.e('获取下载目录失败: $e');
    }
    
    return null;
  }
}